package com.uu.husky.html2pdf;

import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.FSEntityResolver;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 描述：
 *
 * @author liupenghao
 * @create 2018-04-13 21:43
 **/
public class Html2Pdf {
    public static void html2pdf(String InputHtmlFilePath ,String OutPutPdfFilePath) {
        try {
            OutputStream os = new FileOutputStream(new File(OutPutPdfFilePath));
            // initializing iText rendrer
            ITextRenderer renderer = new ITextRenderer();
            // building document factory to render pdf
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            // turning off factory settings to improve generation speed
            fac.setNamespaceAware(false);
            fac.setValidating(false);
            fac.setFeature("http://xml.org/sax/features/namespaces", false);
            fac.setFeature("http://xml.org/sax/features/validation", false);
            fac.setFeature(
                    "http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
                    false);
            fac.setFeature(
                    "http://apache.org/xml/features/nonvalidating/load-external-dtd",
                    false);

            DocumentBuilder builder = fac.newDocumentBuilder();
            builder.setEntityResolver(FSEntityResolver.instance());
            // parsing URL HTML document
            org.w3c.dom.Document document = builder.parse(InputHtmlFilePath);
            renderer.setDocument(document, InputHtmlFilePath);
            // creating pdf layout
            renderer.layout();
            try {
                // generating pdf
                renderer.createPDF(os);
            } catch (Exception e) {
                e.printStackTrace();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Html2Pdf.html2pdf("result.html","result.pdf");
    }
}

